package se.schtohan.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import se.schtohan.model.Book;
import se.schtohan.model.ShoppingCart;
import se.schtohan.service.BookService;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Controller
@SessionAttributes("shoppingCart")
public class BookController {

    private final BookService bookService;

    @Autowired
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping(value="/books", method= RequestMethod.GET)
    public String viewBooks(Model model) {
        ShoppingCart shoppingCart = new ShoppingCart();
        if(!model.containsAttribute("shoppingCart")) {
            model.addAttribute("shoppingCart", shoppingCart); //Eftersom det finns ett SessionAttribute som heter "shoppingCart" kommer en tillägg av samma namn i modellen av leda till att modellens "shoppingCart" blir ett SessionAttribute
        }
        model.addAttribute("books", bookService.getAllBooks());
        return "books";
    }

    @RequestMapping(value="/books", method= RequestMethod.POST)
    public String addBooksToCart(@Valid @ModelAttribute("book") Book book, BindingResult result, Model model) {
        if(result.hasErrors()) {
            return "redirect: books";
        }
        ShoppingCart shoppingCart = (ShoppingCart) model.asMap().get("shoppingCart");
        shoppingCart.addBook(book);
        List<Book> books = bookService.getAllBooks();
        model.addAttribute("books", books);
        return "books";
    }

    @RequestMapping(value="/addbook", method= RequestMethod.GET)
    public String getAddBook(Model model) {
        return "addbook";
    }

    @RequestMapping(value="/addbook", method= RequestMethod.POST)
    public String postAddBook(@Valid @ModelAttribute("book") Book book, BindingResult result, Model model) {
        if(result.hasErrors()) {
            return "redirect: addbook";
        }
        bookService.save(book);
        return "addbook";
    }

}
